package vip.wangwenhao.sso.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.bind.annotation.*;
import vip.wangwenhao.autoconfigure.utils.Oauth2Utils;
import vip.wangwenhao.common.enums.ResultCode;
import vip.wangwenhao.common.result.Result;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/api")
public class LoginController {

    @Autowired
    @Qualifier("consumerTokenServices")
    private ConsumerTokenServices consumerTokenServices;

    @Autowired
    private TokenStore tokenStore;

    @GetMapping(value = "/user",produces = {"application/json;charset=UTF-8"})
    public Object user(HttpServletRequest request) {
        String token = Oauth2Utils.getToken(request);
        if (StringUtils.isNotBlank(token)){
            OAuth2Authentication oAuth2Authentication = tokenStore.readAuthentication(token);
            if (null != oAuth2Authentication){
                if (null == SecurityContextHolder.getContext().getAuthentication()){
                    SecurityContextHolder.getContext().setAuthentication(oAuth2Authentication);
                }
                return oAuth2Authentication.getPrincipal();
            }
        }
        return null;
    }

    @DeleteMapping(value = "/logout")
    public Result revokeToken(String access_token) {
        //注销当前用户
        Result result = new Result();
        if (consumerTokenServices.revokeToken(access_token)) {
            result.setCode(ResultCode.SUCCESS.getCode());
            result.setMessage("注销成功");
        } else {
            result.setCode(ResultCode.ERROR_SERVER_FAILED.getCode());
            result.setMessage("注销失败");
        }
        log.info("logout result={}", result);
        return result;
    }
}